import React from "react";
import { Form, Row, Col } from "antd";
import moment from "moment";
import "./index.scss";

interface IColumnProps {
    label: string;  // 组件的label
    component: React.ComponentType;  // 渲染的可编辑组件
    componentStr: string;  // 组件的字符串
    field: string;  // 字段对应的key值
    extra: {[key: string]: any};  // 传递给组件的额外的属性，这部分由每个组件进行属性编辑时候自行搜集整理
    formExtra: {[key: string]: any};  // 传递给form.Itemd的额外属性
    wrapperComp?: React.ComponentType;  // 包裹Form.item的容器，仅在编辑时使用
}

interface IVFormWrapperProps {
    title: string;
    columns: IColumnProps[];
    layout?: string; // 排列方式
    labelSpan?: number;  // label宽度
    controlSpan?: number;  // 控件宽度
    colNum?: number;  // 列数
    onFinish?: (values: any) => void;
    formExtra?: {[key: string]: any};
}

const VFormWrapper: React.FC<IVFormWrapperProps> = (props) => {
    const { title, columns, layout = "horizontal", labelSpan = 6, controlSpan = 18, colNum = 1 } = props;
    const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: labelSpan },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: controlSpan },
        },
    };
    const renderFormRow = () => {
        const compList = [];
        const rowNum = Math.ceil(columns.length / colNum);
        const colSpan = Math.floor(24 / colNum);
        for(let i = 0; i < rowNum; i++){
            const curColumns = columns.slice(i * colNum, i * colNum + colNum);
            compList.push(<Row>
                {
                    curColumns.map(config => {
                        const Component = config.component;
                        const Wrapper = config.wrapperComp;
                        const FormItem = (<Form.Item
                            label={config.label} name={config.field} {...config.formExtra} 
                            initialValue={(config.formExtra.initialValue && config.componentStr === "DatePicker") ? moment(config.formExtra.initialValue) : config.formExtra.initialValue}
                        >
                            <Component {...config.extra} />
                        </Form.Item>)
                        return <Col span={colSpan}>
                            {
                                Wrapper ? <Wrapper>{FormItem}</Wrapper> : FormItem
                            }
                        </Col>
                    })
                }
            </Row>)
        }
        return compList;
    }
    return (<div className="v-form-wrapper">
        <div className="v-form-header">
            <h5>{title}</h5>
        </div>
        <Form {...formItemLayout} layout={(layout as any)} {...props.formExtra}>
            {
                renderFormRow()
            }
        </Form>
    </div>)
}

export default VFormWrapper;